package models

import (
	"crypto/md5"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/pkg/errors"
	"strconv"
)

type ErpProductsSnd struct {
	Id             int64        `json:"id"`
	Products       *ErpProducts `orm:"rel(fk);null;on_delete(do_nothing)" json:"-"`
	Md5            string       `json:"-"`
	Sph            string       `json:"sph" form:"sph"`
	Cyl            string       `json:"cyl" form:"cyl"`
	Add            string       `json:"add" form:"add"`
	SphInt         float64      `json:"-"`
	CylInt         float64      `json:"-"`
	AddInt         float64      `json:"-"`
	Model          string       `json:"model" form:"model"`
	Color          string       `json:"color" form:"color"`
	Size           string       `json:"size" form:"size"`
	FilmColor      string       `json:"film_color" form:"film_color"`
	FunctionInfo   string       `json:"function_info" form:"function_info"`
	Genre          string       `json:"genre" form:"genre"`
	SuggestedPrice float64      `json:"suggested_price"`                  //销售价格
	TradePrice     float64      `json:"trade_price"`                      //批发价格
	Status         int          `json:"status"`
}

func (a *ErpProductsSnd) TableName() string {
	return ErpProductsSndTableName()
}

func ErpProductsSndTableName() string {
	return TableName("erp_products_snd")
}

//查询
type ErpProductsSndQueryParam struct {
	BaseQueryParam
	Products   int64  `json:"product_id"`
	Department int64  `json:"department_id"`
	Typeid     int    `json:"typeid"`
	Filter     string `json:"filter"`
	Status     int    `json:"status"`
}

func ErpProductsSndPageList(params *ErpProductsSndQueryParam) ([]*ErpProductsSnd, int64) {
	ls := make([]*ErpProductsSnd, 0)
	query := orm.NewOrm().QueryTable(ErpProductsSndTableName())
	cond := orm.NewCondition()

	if params.Products > 0 {
		cond = cond.And("Products__Id", params.Products)
	}
	if len(params.Filter) > 0 {
		cond1 := orm.NewCondition()
		switch params.Typeid {
		case 10:
			_cond := cond1.Or("sph", params.Filter).Or("cyl", params.Filter)
			cond = cond.AndCond(_cond)
		case 20:
			_cond := cond1.Or("sph", params.Filter).Or("cyl", params.Filter)
			cond = cond.AndCond(_cond)
		case 30:
			_cond := cond1.Or("model", params.Filter).Or("color", params.Filter).Or("size", params.Filter)
			cond = cond.AndCond(_cond)
		case 40:
			_cond := cond1.Or("sph", params.Filter).Or("add", params.Filter)
			cond = cond.AndCond(_cond)
		case 41:
			_cond := cond1.Or("model", params.Filter).Or("color", params.Filter).Or("size", params.Filter)
			cond = cond.AndCond(_cond)
		case 70:
			_cond := cond1.Or("Norms__contains", params.Filter).Or("PlaceOrigin__contains", params.Filter).Or("Dnumber__contains", params.Filter)
			cond = cond.AndCond(_cond)
		}
	}
	if params.Status > 0 {
		cond = cond.And("Status", params.Status)
	}

	query = query.SetCond(cond)
	sortorder := "-Id"
	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	total, _ := query.Count()
	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)
	return ls, total
}

func createSndMd5(d *ErpProductsSnd) string {
	var md5string string
	md5string = fmt.Sprintf("%d%s%s%s%s%s%s%s%s%s%s", d.Products.Id, d.Sph, d.Cyl, d.Model, d.Color, d.FilmColor, d.FunctionInfo, d.Genre, d.Size, d.Add)
	return fmt.Sprintf("%x", md5.Sum([]byte(md5string)))
}

//写入SND数据
func ErpProductsSndSave(o orm.TxOrmer, d *ErpProductsSnd) error {
	if d.Id > 0 {
		return nil
	}
	if d.Products.Id == 0 {
		return errors.New("Snd商品参数错误")
	}

	//生成MD5
	has := createSndMd5(d)

	o.QueryTable(ErpProductsSndTableName()).Filter("md5", has).One(d)
	if d.Id == 0 {
		d.Status = 1
		d.Md5 = has
		d.SphInt, _ = strconv.ParseFloat(d.Sph, 64)
		d.CylInt, _ = strconv.ParseFloat(d.Cyl, 64)
		d.AddInt, _ = strconv.ParseFloat(d.Add, 64)
		if _, err := o.Insert(d); err != nil {
			return err
		}
	}
	return nil
}

//更新数据
func ErpProductsSndUpdate(o orm.Ormer, snd *ErpProductsSnd) error {

	if snd.Products.Id == 0 {
		return errors.New("Snd商品参数错误")
	}
	if len(snd.Sph) <= 0 && len(snd.Cyl) <= 0 && len(snd.Model) <= 0 && len(snd.Color) <= 0 {
		return errors.New("Snd商品参数错误")
	}
	//重建HAS值
	snd.Md5 = createSndMd5(snd)
	if _, err := o.Update(snd); err != nil {
		return err
	}
	return nil
}

//更新状态
func ErpProductsSndStauts(id []int64, status int) error {

	_, err := orm.NewOrm().QueryTable(ErpProductsSndTableName()).Filter("id__in", id).Update(orm.Params{
		"Status": status,
	})
	if err != nil {
		return err
	}
	return nil
}

func GetErpProductsSndById(id int64) *ErpProductsSnd {
	snd := new(ErpProductsSnd)
	snd.Id = id
	orm.NewOrm().Read(snd)
	return snd
}
